<?php
namespace app\controllers\shop;
/**
* @desc 调用shop 接口
* @author liaojianwen
* @date 2017-03-17
*/

use Yii;
use yii\web\Controller;
use app\controllers\BaseController;
use app\helpers\scmTokenTool;
use app\helpers\CInputFilter;
use app\models\ProductModel;
use app\models\CategoryModel;
use app\models\SaleOutSyncModel;
use app\dao\ProductDAO;
			 
 class ApiController extends Controller
 {
 	public $enableCsrfValidation = false;
 	/**
	 *@desc 默认控制器
	 *@author liaojianwen
	 *@date 2017-03-17
 	 */
 	public function actionIndex()
 	{
 	}
 	
 	/**
 	 * @desc 返回json数据
 	 * @param $data
 	 * @author liaojianwen
 	 * @date 2016-11-1
 	 */
 	public function renderJson($data)
 	{
 		header('Content-type: application/json');
 		echo json_encode($data);
 		exit;
 	}
 	
 	/**
 	 * @desc 检测 是否是从商城过来的数据
 	 * @author liaojianwen
 	 * @date 2017-03-21
 	 */
    private function scmShopCheck()
    {
    	$headers = Yii::$app->request->headers;
    	$key = $headers->get('authorization');
		if(! scmTokenTool::getInstance()->verifyKey($key)){
            $result = array(
                'Ack' => 'Failure',
                'body' => 'verify error.'
            );
            $this->renderJson($result);
            Yii::$app->end(); // safe
        }
    }
    
    /**
     * @desc 商城新增商品数据
     * @author liaojianwen
     * @date 2017-03-21
     */
    public function actionProductInsert()
    {
    	$this->scmShopCheck();
    	
    	$res = Yii::$app->request;
    	$productInfo = $res->post();
    	$result = ProductModel::model()->shopInsertProduct($productInfo);
    	$this->renderJson($result);
    }

	/**
	 * @desc 商城新增类目
	 * @author liaojianwen
	 * @date 2017-03-21
	 */
    public function actionCategoryInsert()
    {
    	$this->scmShopCheck();
    	
    	$resquest = Yii::$app->request;
    	$categoryInfo = $resquest->post();
    	$result = CategoryModel::model()->shopInsertCategory($categoryInfo);
    	$this->renderJson($result);
    }

	/**
	 * @desc 同步所有产品库存
	 * @author lizichuan
	 * @date 2017-07-29
	 */
    public function actionSyncStock()
    {
    	$product_id = Yii::$app->request->get('product_id', 0);
		
		if ($product_id)
		{
			$products = [['product_id'=>$product_id]];
		}
		else
		{
			// $products = ProductDAO::getInstance()->iselect(['product_id'], "quantity!=0", [], 'all');
			$products = array();
		}
		
		$count = 0;
		foreach ($products as $product)
		{
			$result = ProductDAO::syncStockToShop($product['product_id'], 0);
			if ($result == 'OK')
			{
				$count++;
			}
		}
		echo 'sync total: '.$count;
    }
	
    /**
     * @desc 商城订单新增销售出库单
     * @author lizichuan
     * @date 2018-02-26
     */
    public function actionSaleOutInsert()
    {
    	$this->scmShopCheck();
    	$res = Yii::$app->request;
    	$productInfo = $res->post();
		$result = SaleOutSyncModel::model()->storeInsertSaleOut($productInfo);
    	$this->renderJson($result);
    }
 }
 